<?php 
	class VisitorModel extends Model{
		private function checkDay($time=""){
			if($time!=""&&!empty($time)){
				$current=explode(" ",date("Y-m-d H:i:s"));$current=$current[0];$current=explode("-",$current);
				$time=explode(" ",$time);$time=$time[0];$time=explode("-",$time);
				if($current[0]>$time[0])return true;
				if($current[0]==$time[0]&&$current[1]>$time[1])return true;
				if($current[0]==$time[0]&&$current[1]==$time[1]&&$current[2]>$time[2])return true;
				return false;
			}
		}
		private function saveRecord($fields=array()){
			$this->open(Model::MYSQL);
			if(is_array($fields) && !empty($fields)){
				foreach ($fields AS $field=>$value){
					$fieldname[] = $field ;
					$fieldvalue[] = $value ;
				}
				$query = "INSERT INTO Visitors(" . implode(" , " , $fieldname) . ") VALUES('" . implode("' , '" , $fieldvalue). "')";
				return mysql_query( $query ) ;
			}
		}
				
		private function updateRecord($id,$fields=array()){
			$this->open(Model::MYSQL);
			if(is_array($fields) && !empty($fields)){
				foreach ($fields AS $fieldname=>$fieldvalue){
					$tmp[] = $fieldname . "='" . $fieldvalue . "'";
				}
				$query = "UPDATE Visitors SET " . implode(" , " , $tmp) . " WHERE v_id =" . $id . "";
				return mysql_query( $query ) ;
			}
		}
		private function queryRecord(){
			$this->open(Model::MYSQL);
			$result = mysql_query("SELECT * FROM Visitors ORDER BY modified DESC LIMIT 1") ;
			$records = array();
			while($record = mysql_fetch_object($result)) $records = $record ;
			return $records;
		}
		public function getCounter(){
			$this->open(Model::MYSQL);
			$records = $this->queryRecord();
			$freq = 2;
			$today = $records->today + $freq ;
			$yesterday = $records->yesterday + 0;
			$allday = $records->allday + $freq ;
			
			if($this->checkDay($records->modified)){
				$this->saveRecord(array("today"=>0,"yesterday"=>$records->today,"allday"=>$allday,"modified"=>date("Y-m-d H:i:s")));	
				$records = $this->queryRecord();
				$freq = 2;
				$today = $records->today + $freq ;
				$yesterday = $records->yesterday + 0;
				$allday = $records->allday + $freq ;
			}else{
				//update record if checkday false
				$this->updateRecord($records->v_id,array("today"=>$today,"yesterday"=>$yesterday,"allday"=>$allday,"modified"=>date("Y-m-d H:i:s")));
			}
			return array("today"=>$today,"yesterday"=>$yesterday,"allday"=>$allday);
		}
	}
?>
